package com.collage.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.collage.entity.Bill;
import com.collage.service.BillService;
import com.collage.util.ExcelUtil;
import com.collage.util.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiezz
 * @version 1.0
 * @date 2022/7/5
 */
@Slf4j
@RestController
@RequestMapping("/bill")
@AllArgsConstructor

public class BillController {
    public final BillService service;

    @PostMapping("/save")
    public Result saveBill(@RequestBody Bill bill) {
        return service.save(bill) ? Result.success() : Result.failed("新增失败");
    }

    @PostMapping("/saveAll")
    public Result saveAABill(@RequestBody Bill bill) {
        QueryWrapper<Bill> qw = new QueryWrapper<>();
        qw.lambda().eq(Bill::getAid, bill.getAid());
        List<Bill> bills = service.list(qw);
        if (CollectionUtils.isEmpty(bills)) {
            return Result.failed("暂无参加活动的团员可添加");
        }
        for (Map.Entry<String, List<Bill>> map : bills.stream().collect(Collectors.groupingBy(Bill::getUid)).entrySet()) {
            Bill entity = new Bill();
            Bill copy = map.getValue().get(0);
            entity.setUid(copy.getUid());
            entity.setUserName(copy.getUserName());
            entity.setAid(copy.getAid());
            entity.setActivitiesName(copy.getActivitiesName());
            entity.setName(bill.getName());
            entity.setPrice(bill.getPrice());
            service.save(entity);
        }
        return Result.success();
    }

    @GetMapping("/list/{aid}")
    public Result getBillList(@PathVariable String aid) {
        QueryWrapper<Bill> qw = new QueryWrapper<>();
        qw.lambda().eq(Bill::getAid, aid);
        return Result.success(service.list(qw));
    }

    @PostMapping("/export/{aid}")
    public void exportData(HttpServletResponse response, @PathVariable String aid) {
        QueryWrapper<Bill> qw = new QueryWrapper<>();
        qw.lambda().eq(Bill::getAid, aid);
        ExcelUtil.ExportExcel(response, "活动账单" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()),
                "sheet", Bill.class, service.list(qw));
    }
}
